package pool

import (
	"bytes"
	"context"
	"fmt"

	"github.com/PuerkitoBio/goquery"
	"xtsec.com/dns-syncer/common/tools"
)

const (
	toolLuLookup = "https://tool.lu/ip/"
)

type toolLu struct{ base }

func NewToolLu() *toolLu {
	return &toolLu{base: base{lookup: toolLuLookup, target: "tool.lu"}}
}

func (toolLu toolLu) GetIPResponse(ctx context.Context) (IPResponse, error) {
	ir := IPResponse{Target: toolLu.target}

	var buf bytes.Buffer
	err := toolLu.client().UserAgent(tools.RandChoice[string](uaList)).ToBytesBuffer(&buf).Fetch(ctx)
	if err != nil {
		return ir, err
	}

	doc, err := goquery.NewDocumentFromReader(bytes.NewReader(buf.Bytes()))
	if err != nil {
		return ir, err
	}

	node := doc.Find("#main_form > p:nth-child(3)").First()
	if node == nil {
		return ir, fmt.Errorf("empty node found")
	}

	ip, err := tools.MatchIp(node.Text())
	if err != nil {
		return ir, err
	}

	ir.Ip = ip

	if err := tools.ValidateStruct(ir); err != nil {
		return ir, err
	}

	return ir, nil
}
